package com.sghj.SysPermission.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sghj.SysPermission.entity.SysUser;
import com.sghj.SysPermission.entity.SysUserrole;
import com.sghj.SysPermission.entity.Vo.userAddVo;
import com.sghj.SysPermission.entity.Vo.userLoginVo;
import com.sghj.SysPermission.entity.Vo.userShowVo;
import com.sghj.SysPermission.mapper.SysUserMapper;
import com.sghj.SysPermission.service.SysUserService;
import com.sghj.SysPermission.service.SysUserroleService;
import com.sghj.config.handler.ResultCode;
import com.sghj.config.handler.exceptionHandler.MyException;
import com.sghj.utils.JwtUtils;
import com.sghj.utils.annotation.DataScope;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xrx
 * @since 2022-02-18
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Value("${pwd.manage}")
    private String rePwd;

    @Autowired
    private SysUserroleService userroleService;

    /**
     * 登录返回账号
     * @param username
     * @return
     */
    @Override
    public SysUser handleLogin(String username,String password) {
        //用户名为空或密码为空
        if(StringUtils.isEmpty(username)||StringUtils.isEmpty(password)){
            throw new UnknownAccountException("此账号不存在");
        }
        SysUser user = baseMapper.selectUserByUserName(username);

        //验证账号
        if (user ==null){
            throw new UnknownAccountException("此账号不存在");
        }
        return user;
    }

    /**
     * 生成token
     * @param userInfo
     * @return
     */
    @Override
    public String createToken(userLoginVo userInfo) {
        SysUser user = baseMapper.selectOne(new QueryWrapper<SysUser>().eq("SysUserName", userInfo.getUserName()));
        if (user ==null){
            throw new MyException(20001,"该账号不存在");
        }

        String token = JwtUtils.getJwtToken(user.getSysUserId(), user.getSysUserName());

        return token;
    }

    /**
     * 获取当前用户权限
     * @param sysUserId
     * @return
     */
    @Override
    public Set<String> getUserMenu(Integer sysUserId) {
        return baseMapper.getUserMenu(sysUserId);
    }

    /**
     * 获取当前登录用户信息
     * @param
     * @return
     */
    @Override
    public userShowVo getUserInfoByToken() {
        Subject currentUser = SecurityUtils.getSubject();
        SysUser user = (SysUser)currentUser.getPrincipal();

        if (user ==null){
            throw new MyException(20001,"用户未登录，没有获取到用户信息");
        }
        userShowVo userInfo = baseMapper.getUserDetails(user.getSysUserId());
        return userInfo;
    }

    /**
     * 新增用户
     * @param user
     * @return
     */
    @Transactional
    @Override
    public int addUser(userAddVo user) {
        //新增用户
        if (user.getUserType()!=null&&user.getUserType().equals("1")){
            throw new MyException(ResultCode.NOPERMISSIONS,"没有权限添加超级管理员");
        }
        if (user.getSysUserName()!=null&&baseMapper.selectCount(new QueryWrapper<SysUser>().eq("SysUserName", user.getSysUserName()))>0){
            throw new MyException(ResultCode.PARAMETER,"该用户名已存在");
        }
        if (user.getPwd()==null||user.getPwd().equals("")){
            throw new MyException(ResultCode.PARAMETER,"请输入密码");
        }

        //构建user对象
        SysUser newUser = new SysUser();
        BeanUtils.copyProperties(user,newUser);
        newUser.setPwd(new Md5Hash(user.getPwd(), "zjcq666",1024).toString());
        int insert = baseMapper.insert(newUser);
        //新增用户-角色关联信息
        insertUserRole(user,newUser);
        return insert;
    }

    /**
     * 添加用户角色关联信息
     */
    public void insertUserRole(userAddVo user,SysUser newUser) {

        int[] roleIds = user.getRoleIds();
        if (roleIds!=null&&roleIds.length>0){
            // 新增用户与角色管理
            List<SysUserrole> list = new ArrayList<SysUserrole>();
            for (Integer roleId : roleIds)
            {
                SysUserrole ur = new SysUserrole();
                ur.setSysUserId(newUser.getSysUserId());
                ur.setSysRoleId(roleId);
                list.add(ur);
            }
            if (list.size()>0){
                userroleService.saveBatch(list);
            }
        }
    }

    /**
     * 修改用户信息
     * @param user
     * @return
     */
    @Override
    @Transactional
    public int updateUser(userAddVo user) {
        if (user.getUserType()!=null&&user.getUserType().equals("1")){
            throw new MyException(ResultCode.NOPERMISSIONS,"没有权限添加超级管理员");
        }
        if (user.getSysUserName()!=null&&baseMapper.selectCount(new QueryWrapper<SysUser>().eq("SysUserName", user.getSysUserName()).ne("SysUserId",user.getSysUserId()))>0){
            throw new MyException(ResultCode.PARAMETER,"该用户名已存在");
        }

        SysUser newUser = new SysUser();
        //更新用户信息
        BeanUtils.copyProperties(user,newUser);
        if (user.getPwd()!=null) {
            newUser.setPwd(new Md5Hash(user.getPwd(), "zjcq666", 1024).toString());
        }
        //int row = baseMapper.updateUser(newUser);
        int row = baseMapper.updateById(newUser);
        //如果修改角色
        if (user.getRoleIds()!=null) {
            //删除用户-角色信息
            removeUserRole(user);
            //新增用户-角色信息
            insertUserRole(user, newUser);
        }
        return row;
    }

    /**
     * 根据id查询用户信息
     * @param userId
     * @return
     */
    @Override
    public userAddVo getUserInfoById(Integer userId) {
        //查询用户信息
        userAddVo userVo = new userAddVo();
        SysUser user = baseMapper.selectById(userId);
        BeanUtils.copyProperties(user,userVo);
        //查询用户-角色信息
        List<SysUserrole> sysUserList = userroleService.list(new QueryWrapper<SysUserrole>().eq("SysUserId", userId));
        int[] roles = new int[sysUserList.size()];
        int i =0;
        for (SysUserrole sysUserrole : sysUserList) {
            roles[i++] = sysUserrole.getSysRoleId();
        }
        userVo.setRoleIds(roles);
        return userVo;
    }

    /**
     * 分页条件查询用户信息
     */
    @Override
    @DataScope(deptAlias = "d")
    public IPage<userShowVo> getUserPage(SysUser user,IPage<userShowVo> page) {
        IPage<userShowVo> userPage= baseMapper.getUserPage(page,user);
        return userPage;
    }

    /**
     * 给用户分配角色
     * @param uid
     * @param roles
     * @return
     */
    @Override
    @Transactional
    public boolean allocatRoles(Integer uid, int[] roles) {
        //删除原有角色信息
        userroleService.remove(new QueryWrapper<SysUserrole>().eq("SysUserId",uid));
        //添加新的角色信息
        List<SysUserrole> userroleList = new ArrayList<>();
        for (int role : roles) {
            SysUserrole userrole = new SysUserrole();
            userrole.setSysUserId(uid);
            userrole.setSysRoleId(role);
            userroleList.add(userrole);
        }
        return userroleService.saveBatch(userroleList);
    }

    /**
     * 获取角色列表
     * @param sysUserId
     * @return
     */
    @Override
    public Set<String> getUserRoles(Integer sysUserId) {
        Set<String> roles= baseMapper.getUserRoles(sysUserId);
        return roles;
    }

    /**
     * 重置密码
     * @param uid
     * @return
     */
    @Override
    public int resetPassword(Integer uid) {
        SysUser sysUser = baseMapper.selectById(uid);
        if (sysUser==null){
            throw new MyException(ResultCode.NOTQUERIED,"该用户不存在");
        }
        SysUser newUser = new SysUser();
        newUser.setSysUserId(uid);
        newUser.setPwd(new Md5Hash(rePwd, "zjcq666",1024).toString());
        return baseMapper.updateById(newUser);
    }

    /**
     * 修改密码
     * @param uid
     * @param pwd
     * @return
     */
    @Override
    public int updatePassword(Integer uid, String pwd,String oldpwd) {

        String olduserpwd=getById(uid).getPwd();
        String oldnew=new Md5Hash(oldpwd, "zjcq666",1024).toString();
        if(!oldnew.equals(olduserpwd)){
            throw new MyException(20001,"原密码输入错误，请重新输入");
        }
        if(olduserpwd.equals(new Md5Hash(pwd, "zjcq666",1024).toString())){
            throw new MyException(20001,"新旧密码相同，请重新输入");
        }

        SysUser user = new SysUser();
        user.setSysUserId(uid);
        user.setPwd(new Md5Hash(pwd, "zjcq666",1024).toString());

        return baseMapper.updateById(user);
    }

    /**
     * 删除用户-角色信息
     * @param user
     */
    public void removeUserRole(userAddVo user) {
        QueryWrapper<SysUserrole> wrapper = new QueryWrapper<>();
        wrapper.eq("SysUserId",user.getSysUserId());
        userroleService.remove(wrapper);
    }
}
